<template>
  <el-container class="login-container">
    <el-header class="login-container-header theme-font" height="auto">
      <h1>
        {{ header }}
      </h1>
    </el-header>
    <el-main class="login-container-main">
      <el-form ref="form" :model="form" :rules="rules" @keyup.enter.native="submit('form')">
        <el-form-item prop="loginName">
          <el-input v-model="form.loginName" placeholder="输入用户名或邮箱"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="输入密码"/>
        </el-form-item>
        <el-form-item>
          <el-button class="login-container-main-submit" type="primary" @click="submit('form')">
            登录
          </el-button>
          <el-button class="login-container-main-register" type="text" @click="register">
            没有账号，注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<script>
import apisBinder from '@/axios/user';
import { successMsg } from '@/utils/message';

export default {
  name: 'LoginPage',
  data() {
    return {
      header: '欢迎使用todolist',
      main: '登录表单',
      form: {
        loginName: '',
        password: ''
      },
      rules: {
        loginName: [
          { required: true, message: '输入用户名或邮箱', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '输入密码', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.apis = apisBinder(this);
  },
  methods: {
    submit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const result = await this.apis.login({
            loginName: this.form.loginName,
            password: this.form.password
          });
          if (result.success) {
            await this.$router.push('/home');
            successMsg('登录成功');
          }
        } else {
          return false;
        }
      });
    },
    register() {
      this.$router.push('/register');
    }
  }
};
</script>

<style scoped lang="scss">
.login-container {
  max-width: 500px;
  min-width: 300px;

  &-header {
    text-align: center;

    h1 {
      font-size: 2em;
      font-weight: 700;
    }
  }

  &-main {
    &-submit {
      width: 100%;
    }

    &-register {
      width: 100%;
    }
  }
}
</style>
